package com.baidu.iit.pxp.parser;

import com.baidu.iit.pxp.constants.BpmnXMLConstants;
import com.baidu.iit.pxp.model.BpmnModel;
import com.baidu.iit.pxp.model.ItemDefinition;
import com.baidu.iit.pxp.util.BpmnXMLUtil;
import org.apache.commons.lang3.StringUtils;

import javax.xml.stream.XMLStreamReader;

/**
 * User: huangweili
 * Date: 14-4-26
 * Time: 下午1:59
 */
public class ItemDefinitionParser {


    /**
     * 读取xml文件中的属性定义
     * @param xtr
     * @param model
     * @throws Exception
     */
    public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
        if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_ID))) {
            String itemDefinitionId = model.getTargetNamespace() + ":" + xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_ID);
            String structureRef = xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_STRUCTURE_REF);
            if (StringUtils.isNotEmpty(structureRef)) {
                ItemDefinition item = new ItemDefinition();
                item.setId(itemDefinitionId);
                BpmnXMLUtil.addXMLLocation(item, xtr);

                int indexOfP = structureRef.indexOf(':');
                if (indexOfP != -1) {
                    String prefix = structureRef.substring(0, indexOfP);
                    String resolvedNamespace = model.getNamespace(prefix);
                    structureRef = resolvedNamespace + ":" + structureRef.substring(indexOfP + 1);
                } else {
                    structureRef = model.getTargetNamespace() + ":" + structureRef;
                }

                item.setStructureRef(structureRef);
                item.setItemKind(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_ITEM_KIND));
                BpmnXMLUtil.parseChildElements(BpmnXMLConstants.ELEMENT_ITEM_DEFINITION, item, xtr, model);
                model.addItemDefinition(itemDefinitionId, item);
            }
        }
    }
}
